"""
一个基于PyQt5开发界面的音乐播放应用.

author: Xie Junming
Last edited: 2022/11/08
"""
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QDesktopWidget, QMainWindow, QAction, qApp, QMessageBox, \
    QProgressBar, QGraphicsView, QGraphicsScene, QGraphicsPixmapItem, QFileDialog
from PyQt5.QtCore import QPoint, pyqtSignal, QThread, QUrl, Qt, QDirIterator
from PyQt5.QtMultimedia import QMediaPlaylist, QMediaPlayer, QMediaContent
from PyQt5.QtGui import QIcon, QPixmap, QImage, QPalette, QBrush
import os
import time
import numpy as np
import cv2

from musicUi import Ui_musicWindow

icon_path = "./icon/"


class mainWindows(QMainWindow, Ui_musicWindow):
    def __init__(self, parent=None):
        super(mainWindows, self).__init__(parent)
        self.setupUi(self)
        self.is_playing = False
        self.player = QMediaPlayer()
        self.currentPlaylist = QMediaPlaylist()

        self.duration = 100.0
        self.currentFile_name_list = []

    def run(self):
        """
        主函数，启动的时候默认加载./media文件下的音乐文件
        :return:
        """
        self.play_btn.clicked.connect(self.on_play_btn)  # 播放按钮的信号与槽
        self.player.positionChanged.connect(self.qmp_positionChanged)  # 进度条的信号与槽
        self.addFiles()
        self.show()

    def on_play_btn(self):
        """
        处理按钮点击
        :return:
        """
        print("播放按钮")
        self.is_playing = ~self.is_playing
        if self.is_playing:
            self.play_btn.setStyleSheet('QPushButton{border-image:url(%s/暂停.png)}' % icon_path)
            self.playHandler()
            self.duration = float(self.player.duration())
            self.insert_photo()
            # self.infoText.setText(self.currentFile_name_list[self.currentPlaylist.mediaCount() - 1])
            self.infoText.setText(self.currentFile_name_list[0])
            # self.displaySongInfo()
            # self.player.play()
        else:
            self.play_btn.setStyleSheet('QPushButton{border-image:url(%s/播放.png)}' % icon_path)
            self.player.stop()
        pass

    def playHandler(self):
        """
        检测play list情况
        :return:
        """
        self.userAction = 1
        # self.statusBar().showMessage('Playing at Volume %d' % self.player.volume())
        if self.player.state() == QMediaPlayer.StoppedState:
            if self.player.mediaStatus() == QMediaPlayer.NoMedia:
                # self.player.setMedia(QMediaContent(QUrl.fromLocalFile(self.currentFile)))
                print("media count", self.currentPlaylist.mediaCount())
                # if self.currentPlaylist.mediaCount() == 0:
                #     self.openFile()
                if self.currentPlaylist.mediaCount() != 0:
                    self.player.setPlaylist(self.currentPlaylist)
            elif self.player.mediaStatus() == QMediaPlayer.LoadedMedia:
                self.player.play()
            elif self.player.mediaStatus() == QMediaPlayer.BufferedMedia:
                self.player.play()
        elif self.player.state() == QMediaPlayer.PlayingState:
            pass
        elif self.player.state() == QMediaPlayer.PausedState:
            self.player.play()

    def qmp_positionChanged(self, position, senderType=False):
        """
        进度条显示，参数由player传过来
        :param position: 进度位置
        """
        self.progressBar.setValue(int(10000 * float(position) / (self.duration + 1)))

    def insert_photo(self):
        """
        将歌声的照片显示，并把模糊加载软件的背景，类似Apple music的操作
        :return:
        """
        graphicsView_size = [160, 160]
        idol_head_photo = icon_path + "geshen.jpg"
        img = cv2.imread(idol_head_photo)  # 读取图像
        img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)  # 转换图像通道
        resize_img = cv2.resize(img, graphicsView_size)

        x = resize_img.shape[1]  # 获取图像大小
        y = resize_img.shape[0]
        frame = QImage(resize_img, x, y, QImage.Format_RGB888)
        pix = QPixmap.fromImage(frame)
        self.item = QGraphicsPixmapItem(pix)  # 创建像素图元
        self.scene = QGraphicsScene()  # 创建场景
        self.scene.addItem(self.item)
        self.photo.setScene(self.scene)

        windows_size = [600, 600]
        windows_size_img = cv2.resize(img, windows_size)

        imgBlur = cv2.GaussianBlur(windows_size_img, (205, 205), 201)  # 高斯模糊
        x = imgBlur.shape[1]  # 获取图像大小
        y = imgBlur.shape[0]
        frame = QImage(imgBlur, x, y, QImage.Format_RGB888)
        pix = QPixmap.fromImage(frame)
        # 界面背景图片设置
        palette = QPalette()
        palette.setBrush(self.backgroundRole(), QBrush(pix))
        # palette.setBrush(QPalette.Background, QBrush(pix))
        self.setPalette(palette)

    def addFiles(self):
        """
        加载./media/文件夹下的音乐媒体
        :return:
        """
        folderChoosen = "./media/"
        file_list = os.listdir(folderChoosen)
        print(file_list)
        if folderChoosen != None:
            for f in file_list:
                if f.split(".")[1] in ('mp3', 'ogg', 'wav'):
                    print('added file ', folderChoosen + f)
                    self.currentFile_name_list.append(f.split(".")[0])
                    self.currentPlaylist.addMedia(QMediaContent(QUrl.fromLocalFile(folderChoosen + f)))
        self.player.setPlaylist(self.currentPlaylist)

if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = mainWindows()
    ex.run()
    sys.exit(app.exec_())
